class MapManager {
    constructor() {
        this.map = null;
        this.geocoder = null;
        this.geolocation = null;
        this.currentTempMarker = null;
        this.currentDriving = null;
        this.currentWalking = null;
        this.currentNavType = 'walking';
        this.locationSelected = false;
    }

    async initialize() {
        window._AMapSecurityConfig = {
            securityJsCode: "[填你自己的高德api 密钥]",
        };

        try {
            const AMap = await AMapLoader.load({
                key: MAP_CONFIG.key,
                version: MAP_CONFIG.version,
                plugins: MAP_CONFIG.plugins
            });

            this.map = new AMap.Map("container", {
                viewMode: '2D',
                zoom: MAP_CONFIG.defaultZoom,
                center: MAP_CONFIG.defaultCenter,
            });

            this.geocoder = new AMap.Geocoder();
            this.geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,
                timeout: 10000,
                buttonPosition: 'RB',
                buttonOffset: new AMap.Pixel(10, 20),
                zoomToAccuracy: true,
                convert: true,
                showButton: true,
                showMarker: true,
                showCircle: true,
                panToLocation: true,
                position: 'RB'
            });

            this.map.addControl(this.geolocation);
            this.initializeEndPoints();
            this.initializeEventListeners();
        } catch (error) {
            console.error('地图初始化失败:', error);
        }
    }

    initializeEndPoints() {
        const endMarkers = MAP_CONFIG.endPoints.map(point => {
            return new AMap.Marker({
                position: point.position,
                title: point.name,
                label: {
                    content: point.name,
                    direction: 'top'
                },
                icon: new AMap.Icon({
                    size: new AMap.Size(25, 34),
                    image: point.icon
                })
            });
        });

        endMarkers.forEach(marker => marker.setMap(this.map));
    }

    initializeEventListeners() {
        this.map.on('click', (e) => {
            if (!this.locationSelected) return;
            
            const position = [e.lnglat.getLng(), e.lnglat.getLat()];
            
            this.geocoder.getAddress(position, (status, result) => {
                let address = '未知地点';
                if (status === 'complete' && result.regeocode) {
                    address = result.regeocode.formattedAddress;
                }
                
                this.createTempMarker(position);
                const nearestEnd = this.findNearestEnd(position);
                this.planRoute(position, address, nearestEnd);
            });
        });
    }

    createTempMarker(position) {
        const tempMarker = new AMap.Marker({
            position: position,
            title: '当前位置',
            label: {
                content: '当前位置',
                direction: 'top'
            },
            icon: new AMap.Icon({
                size: new AMap.Size(25, 34),
                image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_g.png'
            })
        });
        
        if (this.currentTempMarker) {
            this.currentTempMarker.setMap(null);
        }
        
        tempMarker.setMap(this.map);
        this.currentTempMarker = tempMarker;
    }

    findNearestEnd(position) {
        let nearestEnd = null;
        let minDistance = Infinity;

        MAP_CONFIG.endPoints.forEach(endPoint => {
            const distance = this.calculateDistance(position, endPoint.position);
            if (distance < minDistance) {
                minDistance = distance;
                nearestEnd = endPoint;
            }
        });

        return nearestEnd;
    }

    calculateDistance(point1, point2) {
        return AMap.GeometryUtil.distanceOfLine([point1, point2]);
    }

    // 在 planRoute 方法中添加更新楼梯口选择的代码
    planRoute(startPosition, startName, endPoint) {
        window.currentStart = startPosition;
        window.currentStartName = startName;
        window.currentEnd = endPoint;
        
        // 更新楼梯口选择下拉菜单
        if (window.uiManager && endPoint.stairId) {
            window.uiManager.updateStairSelect(endPoint);
        }
        
        if (this.currentDriving) {
            this.currentDriving.clear();
        }
        if (this.currentWalking) {
            this.currentWalking.clear();
        }

        if (this.currentNavType === 'driving') {
            const driving = new AMap.Driving({
                map: this.map,
                panel: "panel"
            });

            driving.search(
                startPosition,
                endPoint.position,
                (status, result) => {
                    if (status === 'complete') {
                        console.log('绘制驾车路线完成');
                        this.currentDriving = driving;
                    } else {
                        console.error('获取驾车数据失败：' + result);
                    }
                }
            );
        } else {
            const walking = new AMap.Walking({
                map: this.map,
                panel: "panel"
            });

            walking.search(
                startPosition,
                endPoint.position,
                (status, result) => {
                    if (status === 'complete') {
                        console.log('绘制步行路线完成');
                        this.currentWalking = walking;
                    } else {
                        console.error('获取步行数据失败：' + result);
                    }
                }
            );
        }

        alert('已选择当前位置：' + startName + '\n经度：' + startPosition[0] + '\n纬度：' + startPosition[1] + 
              '\n\n导航至最近的终点：' + endPoint.name + 
              '\n\n导航方式：' + (this.currentNavType === 'driving' ? '驾车' : '步行'));
    }

    setNavigationType(type) {
        this.currentNavType = type;
        if (window.currentStart && window.currentEnd) {
            this.planRoute(window.currentStart, window.currentStartName, window.currentEnd);
        }
    }
}

// 命令行功能
document.addEventListener('DOMContentLoaded', function() {
    const commandInput = document.getElementById('command-input');
    const runCommandBtn = document.getElementById('run-command-btn');
    const commandOutput = document.getElementById('command-output');
    
    if (runCommandBtn) {
        runCommandBtn.addEventListener('click', runCommand);
    }
    
    if (commandInput) {
        commandInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                runCommand();
            }
        });
    }
    
    function runCommand() {
        const command = commandInput.value.trim();
        if (!command) return;
        
        // 显示正在执行的命令
        appendToOutput(`$ ${command}\n`);
        
        // 发送命令到服务器
        fetch('/api/run_command', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ command })
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                appendToOutput(`错误: ${data.error}\n`);
            } else {
                if (data.stdout) {
                    appendToOutput(data.stdout);
                }
                if (data.stderr) {
                    appendToOutput(`错误输出:\n${data.stderr}`);
                }
                appendToOutput(`\n命令执行完成，退出码: ${data.exit_code}\n\n`);
            }
        })
        .catch(error => {
            appendToOutput(`请求错误: ${error.message}\n`);
        });
        
        // 清空输入框
        commandInput.value = '';
    }
    
    function appendToOutput(text) {
        commandOutput.textContent += text;
        // 滚动到底部
        commandOutput.scrollTop = commandOutput.scrollHeight;
    }
});